<template>
	<div class="ele-body">
		<el-card shadow="never">
			<!-- 搜索表单 -->
			<el-form :model="table.where" label-width="77px" class="ele-form-search" @keyup.enter.native="$refs.table.reload()" @submit.native.prevent>
				<el-row :gutter="15">
					<el-col :md="5" :sm="12">
						<el-form-item label="用户账号:"><el-input v-model="table.where.username" placeholder="请输入" clearable /></el-form-item>
					</el-col>
					<el-col :md="5" :sm="12">
						<el-form-item label="用户名:"><el-input v-model="table.where.nickname" placeholder="请输入" clearable /></el-form-item>
					</el-col>
					<el-col :md="5" :sm="12">
						<el-form-item label="性别:">
							<el-select v-model="table.where.sex" placeholder="请选择" clearable class="ele-fluid">
								<el-option label="男" value="1" />
								<el-option label="女" value="2" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :md="4" :sm="12">
						<div class="ele-form-actions">
							<el-button type="primary" @click="$refs.table.reload()" icon="el-icon-search" class="ele-btn-icon">查询</el-button>
							<el-button @click="(table.where = {}) && $refs.table.reload()">重置</el-button>
						</div>
					</el-col>
				</el-row>
			</el-form>
			<!-- 操作按钮 -->
			<div class="ele-table-tool ele-table-tool-default">
				<el-button @click="showEdit = true" type="primary" icon="el-icon-plus" class="ele-btn-icon" size="mini">添加</el-button>
				<el-button @click="remove()" type="danger" icon="el-icon-delete" class="ele-btn-icon" size="mini">删除</el-button>
				<!-- <el-button @click="showImport = true" icon="el-icon-upload2" class="ele-btn-icon" size="mini">导入</el-button> -->
			</div>
			<!-- 数据表格 -->
			<ele-data-table ref="table" :config="table" :choose.sync="choose" highlight-current-row>
				<template slot-scope="{ index }">
					<el-table-column type="selection" width="45" align="center" fixed="left" />
					<el-table-column type="index" :index="index" width="45" align="center" fixed="left" show-overflow-tooltip />
					<el-table-column prop="username" label="用户账号" sortable="custom" show-overflow-tooltip min-width="110" />
					<el-table-column prop="nickname" label="用户名" sortable="custom" show-overflow-tooltip min-width="110" />
					<el-table-column prop="phone" label="ERP用户编号" sortable="custom" show-overflow-tooltip min-width="110" />
					<el-table-column prop="email" label="所属仓店" sortable="custom" show-overflow-tooltip min-width="110" />
					<el-table-column prop="sexName" label="性别" sortable="custom" show-overflow-tooltip min-width="80" />
					<el-table-column label="角色" show-overflow-tooltip min-width="110">
						<template slot-scope="{ row }">
							<el-tag v-for="item in row.roles" :key="item.roleId" type="primary" size="mini">{{ item.roleName }}</el-tag>
						</template>
					</el-table-column>
					<el-table-column prop="introduction" label="简介" sortable="custom" show-overflow-tooltip min-width="110" />
					<el-table-column label="创建时间" sortable="custom" show-overflow-tooltip min-width="110">
						<template slot-scope="{ row }">
							{{ row.createTime | toDateString }}
						</template>
					</el-table-column>
					<el-table-column prop="state" label="状态" width="75px" sortable="custom" :resizable="false">
						<template slot-scope="{ row }">
							<el-switch v-model="row.state" @change="editState(row)" :active-value="0" :inactive-value="1" />
						</template>
					</el-table-column>
					<el-table-column label="操作" width="200px" align="center" :resizable="false">
						<template slot-scope="{ row }">
							<el-link @click="edit(row)" icon="el-icon-edit" type="primary" :underline="false">修改</el-link>
							<el-popconfirm title="确定要删除此用户吗？" @confirm="remove(row)" class="ele-action">
								<el-link slot="reference" icon="el-icon-delete" type="danger" :underline="false">删除</el-link>
							</el-popconfirm>
								<el-tooltip content="重置用户密码" placement="top">
									<el-popconfirm title="确定要重置此用户密码吗？" @confirm="resetPassword(row)" class="ele-action">
										<el-link slot="reference" icon="el-icon-edit-outline" type="warning" :underline="false">改密</el-link>
									</el-popconfirm>
								</el-tooltip>
						</template>
					</el-table-column>
				</template>
			</ele-data-table>
		</el-card>
		<!-- 编辑弹窗 -->
		<el-dialog
			:title="editForm.userId ? '修改用户' : '添加用户'"
			:visible.sync="showEdit"
			width="700px"
			@closed="editForm = {}"
			:destroy-on-close="true"
			custom-class="ele-dialog-form"
			:lock-scroll="false"
			:close-on-click-modal="false"
		>
			<el-form :model="editForm" ref="editForm" :rules="editRules" label-width="120px">
				<el-row :gutter="15">
					<el-col :sm="12">
						<el-form-item label="用户账号:" prop="username">
							<el-input v-model="editForm.username" placeholder="请输入账号" clearable :disabled="editForm.userId ? true : false" />
						</el-form-item>
						<el-form-item label="用户名:" prop="nickname"><el-input v-model="editForm.nickname" placeholder="请输入用户名" clearable /></el-form-item>
						<el-form-item label="角色:" prop="roleIds">
							<el-select v-model="editForm.roleIds" placeholder="请选择角色" class="ele-block" clearable multiple>
								<el-option v-for="(item, index) in roleList" :key="index" :label="item.roleName" :value="item.roleId" />
							</el-select>
						</el-form-item>
						<el-form-item label="登录密码:" prop="password" v-if="!editForm.userId">
							<el-input v-model="editForm.password" placeholder="请输入登录密码" show-password />
						</el-form-item>
					</el-col>
					<el-col :sm="12">
						<el-form-item label="ERP用户编号:" prop="phone"><el-input v-model="editForm.phone" placeholder="请输入" clearable /></el-form-item>
						<el-form-item label="所属仓店:"><el-input v-model="editForm.email" placeholder="请输入所属仓店" clearable /></el-form-item>
						<el-form-item label="性别:">
							<el-select v-model="editForm.sex" placeholder="请选择性别" class="ele-block" clearable>
								<el-option label="男" :value="1" />
								<el-option label="女" :value="2" />
							</el-select>
						</el-form-item>
						<el-form-item label="个人简介:"><el-input v-model="editForm.introduction" placeholder="请输入个人简介" clearable /></el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<div slot="footer">
				<el-button @click="showEdit = false">取消</el-button>
				<el-button type="primary" @click="save">保存</el-button>
			</div>
		</el-dialog>
		<!-- 用户导入弹窗 -->
		<el-dialog title="导入用户" :visible.sync="showImport" width="440px" :destroy-on-close="true" :lock-scroll="false">
			<el-upload
				v-loading="uploadLoading"
				:action="$http.defaults.baseURL + '/file/upload'"
				accept=".xls,.xlsx"
				:headers="$http.defaults.headers.common"
				:before-upload="() => (uploadLoading = true)"
				class="ele-block"
				:on-success="uploadSuccess"
				:on-error="() => (uploadLoading = false)"
				:show-file-list="false"
				drag
			>
				<i class="el-icon-upload"></i>
				<div class="el-upload__text">
					将文件拖到此处，或
					<em>点击上传</em>
				</div>
				<div class="el-upload__tip ele-text-center" slot="tip">
					只能上传xls、xlsx文件，
					<el-link type="primary" :underline="false" :href="importTplUrl" download style="vertical-align:baseline;">下载模板</el-link>
				</div>
			</el-upload>
		</el-dialog>
	</div>
</template>

<script>
export default {
	name: 'SysUser',
	data() {
		return {
			table: { url: '/sys/user/page', where: {} }, // 表格配置
			choose: [], // 表格选中数据
			showEdit: false, // 是否显示表单弹窗
			editForm: {}, // 表单数据
			editRules: {
				// 表单验证规则
				username: [{ required: true, message: '请输入账号', trigger: 'blur' }],
				nickname: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
				phone: [{ required: true, message: '请输入ERP对应的用户编号', trigger: 'blur' }],
				roleIds: [{ required: true, message: '请输入角色', trigger: 'blur' }],
				password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
			},
			roleList: [], // 角色列表
			showImport: false, // 显示导入弹窗
			uploadLoading: false, // 导入加载状态
			importTplUrl: 'https://cdn.eleadmin.com/20200610/用户导入模板.xlsx' // 导入模板下载地址
		};
	},
	mounted() {
		this.queryRoles(); // 查询角色列表
	},
	methods: {
		/* 显示编辑 */
		edit(row) {
			console.log(row,'row');
			this.editForm = Object.assign({}, row, {
				roleIds: row.roles.map(d => d.roleId)
			});
			console.log(this.editForm,'row1');
			this.showEdit = true;
		},
		/* 保存编辑 */
		save() {
			this.$refs['editForm'].validate(valid => {
				if (valid) {
					const loading = this.$loading({ lock: true });
					const posturl = this.editForm.userId ? '/sys/user/update' : '/sys/user/add';
					
					this.$http
						.post(posturl, this.editForm)
						.then(res => {
							loading.close();
							if (res.data.code === 0) {
								this.showEdit = false;
								this.$message({ type: 'success', message: res.data.msg });
								this.$refs.table.reload();
							} else {
								this.$message.error(res.data.msg);
							}
						})
						.catch(e => {
							loading.close();
							this.$message.error(e.message);
						});
				} else {
					return false;
				}
			});
		},
		/* 删除 */
		remove(row) {
			if (!row) {
				// 批量删除
				if (this.choose.length === 0) return this.$message.error('请至少选择一条数据');
				let ids = this.choose.map(d => d.userId);
				this.$confirm('确定要删除选中的用户吗?', '提示', { type: 'warning' })
					.then(() => {
						const loading = this.$loading({ lock: true });
						this.$http
							.post('/sys/user/removeBatch', { ids: ids })
							.then(res => {
								loading.close();
								if (res.data.code === 0) {
									this.$message({ type: 'success', message: res.data.msg });
									this.$refs.table.reload();
								} else {
									this.$message.error(res.data.msg);
								}
							})
							.catch(e => {
								loading.close();
								this.$message.error(e.message);
							});
					})
					.catch(() => 0);
			} else {
				// 单个删除
				const loading = this.$loading({ lock: true });
				this.$http
					.post('/sys/user/remove?id=' + row.userId)
					.then(res => {
						loading.close();
						if (res.data.code === 0) {
							this.$message({ type: 'success', message: res.data.msg });
							this.$refs.table.reload();
						} else {
							this.$message.error(res.data.msg);
						}
					})
					.catch(e => {
						loading.close();
						this.$message.error(e.message);
					});
			}
		},
		/*重置用户密码*/
		resetPassword(row){
			const loading = this.$loading({ lock: true });
			this.$http
				.post('/sys/user/resetPassword?id='+ row.userId)
				.then(res => {
					loading.close();
					if (res.data.code === 0) {
						this.$message({ type: 'success', message: res.data.msg });
					} else {
						row.state = !row.state ? 1 : 0;
						this.$message.error(res.data.msg);
					}
				})
				.catch(e => {
					loading.close();
					this.$message.error(e.message);
				});
		},
		/* 更改状态 */
		editState(row) {
			const loading = this.$loading({ lock: true });
			this.$http
				.post('/sys/user/state', {'userId': row.userId, 'state': row.state })
				.then(res => {
					loading.close();
					if (res.data.code === 0) {
						this.$message({ type: 'success', message: res.data.msg });
					} else {
						row.state = !row.state ? 1 : 0;
						this.$message.error(res.data.msg);
					}
				})
				.catch(e => {
					loading.close();
					this.$message.error(e.message);
				});
		},
		/* 文件上传成功 */
		uploadSuccess(res) {
			this.uploadLoading = false;
			if (res.code === 0) {
				this.showImport = false;
				this.$message({ type: 'success', message: res.msg });
				this.query();
			} else {
				this.$message.error(res.msg);
			}
		},
		/* 查询角色列表 */
		queryRoles() {
			this.$http
				.get('/sys/role/list')
				.then(res => {
					if (res.data.code === 0) {
						this.roleList = res.data.data;
					} else {
						this.$message.error(res.data.msg);
					}
				})
				.catch(e => {
					this.$message.error(e.message);
				});
		}
	}
};
</script>

<style scoped>
.ele-block >>> .el-upload,
.ele-block >>> .el-upload-dragger {
	width: 100%;
}
</style>
